import React, {useState, useEffect} from 'react'

import {Container} from './style'

import { Button, Input, Table, Space, Switch, Modal, Popconfirm, message} from 'antd'

import {ClearOutlined} from '@ant-design/icons'

import Markdown from '../../../../components/Markdown'

import moment from 'moment'

import ArticleRequest from '../../../../request/article_request'

const article_request  = new ArticleRequest()

function BlogAdmin(){
    const [modalVisible, setModalVisible] = useState(false)
    let tableColunm = 
        [
            {
                title: '序号',
                key: 'number',
                render: (text, record, index) => {
                    return index + 1
                }
            },
            {
                title: '标题',
                dataIndex: 'title',
                key: 'title',
                width: 150
            },
            {
                title: '简要描述',
                dataIndex: 'desc',
                key: 'desc',
                width: 300
            },
            {
                title: '阅读量',
                key: 'readcount',
                dataIndex: 'readcount',
            },
            {
                title: '点赞数',
                key: 'likecount',
                dataIndex: 'likecount',
            },
            {
                title: '收藏数',
                key: 'collectcount',
                dataIndex: 'collectcount',
            },
            {
                title: '创建日期',
                key: 'createdate',
                render: (text, record) => {
                    return moment(Number(record.createdate)).format('YYYY-MM-DD HH:mm:ss')
                }
            },
            {
                title: '更新日期',
                key: 'updateDate',
                render: (text, record) => {
                    return moment(Number(record.updateDate)).format('YYYY-MM-DD HH:mm:ss')
                }
            },
            {
                title: '是否置顶',
                key: 'istop',
                render: (text, record) => (
                    <span>
                        <Switch checkedChildren="是" unCheckedChildren="否" checked={record.istop === '1' ? true : false} onChange={() => articleTop(record.id)}/>
                    </span>
                )
            },
            {
                title: '是否发布',
                key: 'status',
                render: (text, record) => (
                    <span>
                        <Switch checkedChildren="是" unCheckedChildren="否" checked={record.status === '1' ? true : false} onChange={() => articlePublish(record.id)}/>
                    </span>
                )
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <Space>
                        <Button type="primary" size="small" onClick={() => editBlog(record)}>编辑</Button>
                        <Popconfirm
                            title="确定永久删除？"
                            okText="删除"
                            cancelText="暂不"
                            onConfirm={() => deleteArticle(record.id)}
                        >
                            <Button type="primary" size="small" danger>删除</Button>
                        </Popconfirm>
                    </Space>
                ),
            },
        ]
     //表格结构
    const [tableData, setTableData] = useState([]) //表格数据

    const [keyword, setKeyword] = useState('')

    const [confirmLoading, setConfirmLoading] = useState(false)
    const [title, setTitle] = useState('')
    const [desc, setDesc] = useState('')
    const [content, setContent] = useState('')
    const [contentMd, setContentMd] = useState('')
    const [type, setType] = useState('')

    const [clearImgLoading, setClearImgLoading] = useState(false)

    const [id, setId] = useState('')

    useEffect(() => {
        getArticleList()
    }, [])

    const getArticleList = () => {
        article_request.getArticleList({
            title: keyword,
            type: '0'
        }).then(res => {
            setTableData(res.map((item, index) => {
                return {
                    ...item,
                    key: index
                }
            }))
        })
    }

    const articleTop = (id) => {
        article_request.articleTop({
            id
        }).then(res => {
            message.success('操作成功')
            getArticleList()
        })
    }

    const articlePublish = (id) => {
        article_request.articlePublish({
            id
        }).then(res => {
            message.success('操作成功')
            getArticleList()
        })
    }

    const addBlog = () => {
        setModalVisible(true)
        setType('add')
        setContentMd('')
        setContent('')
        setTitle('')
        setDesc('')
    }

    const editBlog = (record) => {
        setModalVisible(true)
        setContentMd(record.contentMd)
        setContent(record.content)
        setTitle(record.title)
        setDesc(record.desc)
        setType('edit')
        setId(record.id)
    }
    
    const getArticleContent = (html, md) => {
        setContent(html)
        setContentMd(md)
    }

    const saveDrafts = () => {
        article_request.addArticle({
            title,
            desc,
            content,
            contentMd,
            isDrafts: true
        }).then(res => {
            message.success('保存草稿箱成功！')
            setModalVisible(false)
        })
    }

    const confirmAdd = () => {
        setConfirmLoading(true)
        setTimeout(() => {
            if(type === 'add'){
                article_request.addArticle({
                    title,
                    desc,
                    content,
                    contentMd
                }).then(res => {
                    setConfirmLoading(false)
                    setModalVisible(false)
                    message.success('新增成功！')
                    getArticleList()
                }).catch(err => {
                    setConfirmLoading(false)
                })
            }else{
                article_request.editArticle({
                    title,
                    desc,
                    content,
                    contentMd,
                    id
                }).then(res => {
                    setConfirmLoading(false)
                    setModalVisible(false)
                    message.success('编辑成功！')
                    getArticleList()
                }).catch(err => {
                    setConfirmLoading(false)
                })
            }
        }, 1500)
    }

    const closeModal = () => {
        setModalVisible(false)
        setContentMd('')
        setContent('')
    }

    const deleteArticle = (id) => {
        article_request.deleteArticle({
            id
        }).then(res => {
            message.success('删除成功！')
            getArticleList()
        })
    }

    const clearImage = () => {
        setClearImgLoading(true)
        article_request.clearArticleImage().then(res => {
            setClearImgLoading(false)
            message.success('释放服务器空间成功！')
        })
    }
    return (
        <Container>
            <div className="top">
                <Space>
                    <Button type="primary" onClick={addBlog}>新增博文</Button>
                    <Input placeholder="请输入博文关键字" style={{ width: 200 }} value={keyword} allowClear onChange={(e) => setKeyword(e.target.value)} onPressEnter={getArticleList}></Input>
                    <Button type="primary" onClick={getArticleList}>查询博文</Button>
                    <Button type="primary" icon={<ClearOutlined />} loading={clearImgLoading} onClick={clearImage}>清除未使用图片</Button>
                </Space>
            </div>
            <div className="bottom">
                <Table columns={tableColunm} pagination={{showSizeChanger: true, showTotal: (total) => `共 ${total} 条`}} dataSource={tableData} />
            </div>
            <Modal
                title={
                    <div>
                        <span>{type === 'add' ? '新增' : '编辑'}博文</span>
                        <Space style={{float: 'right'}}>
                            {
                                type === 'add' ? 
                                <Button type="primary" type="text" onClick={saveDrafts}>保存到草稿箱</Button>
                                : ''
                            }
                            <Button type="primary" loading={confirmLoading} onClick={confirmAdd}>确认{type === 'add' ? '新增' : '编辑'}</Button>
                            <Popconfirm
                                title="确定放弃编辑内容？"
                                okText="放弃"
                                cancelText="暂不"
                                onConfirm={closeModal}
                            >
                                <Button danger>放弃{type === 'add' ? '新增' : '编辑'}</Button>
                            </Popconfirm>
                        </Space>
                    </div>
                }
                visible={modalVisible}
                width="84%"
                footer={null}
                destroyOnClose={true}
                closable={false}
                keyboard={false}
                maskClosable={false}
                style={{top: 64}}
                bodyStyle={{height: '80vh'}}
            >
                <div className="blog-container">
                    <div className="title-desc">
                            <Input placeholder="请输入博文标题" style={{ width: 200 }} value={title} onChange={(e) => setTitle(e.target.value)}></Input>
                            <Input placeholder="请输入博文简单描述" style={{ width: '50%', marginLeft: 8 }} value={desc} onChange={(e) => setDesc(e.target.value)}></Input>
                    </div>
                    <div className="content">
                        <Markdown onChange={getArticleContent} value={contentMd}></Markdown>
                    </div>
                </div>
            </Modal>
        </Container>
    )
}

export default BlogAdmin